package com.kznnc.data_structure.current;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Description
 * @Author houchenkai
 * @Created Date: 2021/7/7 17:32
 * @ClassName
 */
public class ReentrantReadWriteLockDemo {

    private static Integer num = 0;

    public static void main(String[] args) {
        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();

        ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
        ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();

        RunnerTask runnerTask = new RunnerTask(readLock, writeLock);

        for (int i = 0; i < 5; i++) {
            new Thread(runnerTask).start();
        }

    }


    static  class  RunnerTask implements Runnable{
        ReentrantReadWriteLock.ReadLock readLock;
        ReentrantReadWriteLock.WriteLock writeLock;

        public RunnerTask(ReentrantReadWriteLock.ReadLock readLock, ReentrantReadWriteLock.WriteLock writeLock) {
            this.readLock = readLock;
            this.writeLock = writeLock;
        }

        @Override
        public void run() {


            try {
                readLock.lock();
                for (int i = 0; i < 100; i++) {
                    num++;
                }
            } finally {
                readLock.unlock();
            }
        }
    }


}
